import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import DefaultLayout from '@/components/layouts/index.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/index.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/',
    component: DefaultLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'ProjectList',
        component: () => import('../views/projects/list.vue')
      },
      {
        path: 'project/create',
        name: 'CreateProject',
        component: () => import('../views/projects/create.vue')
      },
      {
        path: 'project/:id',
        name: 'ProjectDetail',
        component: () => import('../views/projects/detail.vue')
      },
      {
        path: 'project/:id/settings',
        name: 'ProjectSettings',
        component: () => import('../views/projects/setting.vue')
      },
      {
        path: 'deploy',
        name: 'Deploy',
        component: () => import('../views/deploy/index.vue')
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/settings/index.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/notFound/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  try {
    if (authStore.token && !authStore.user) {
      await authStore.fetchUser()
    }

    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!authStore.isAuthenticated) {
        next({ name: 'Login', query: { redirect: to.fullPath } })
      } else {
        next()
      }
    } else if (to.matched.some(record => record.meta.requiresGuest)) {
      if (authStore.isAuthenticated) {
        next({ name: 'ProjectList' })
      } else {
        next()
      }
    } else {
      next()
    }
  } catch (error) {
    console.error('Navigation error:', error)
    authStore.logout()
    next({ name: 'Login' })
  }
})

export default router 